package movee.grpc.server;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * grpc server启停等管理功能
 */
@Component
@Slf4j
public class GrpcServer implements ApplicationRunner {

    private Server server = null;
    private Integer port;

    public GrpcServer(@Value("${grpc.server.port}") Integer port) {
        this.port = port;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        server = ServerBuilder.forPort(port)
                // 添加grpc service
                .addService(new GreeterService())
                .build()
                .start();

        log.info("start grpc server on port({})", port);

        // 添加关闭回调钩子
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    // TODO
                    GrpcServer.this.stop();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                log.info("GreeterServer stoped.");
            }
        });
    }

    public void stop() throws InterruptedException {
        if(this.server != null) {
            this.server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
        }
    }
}
